package top.aylan.org.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.aylan.org.Common.SystemConstants;
import top.aylan.org.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2018/12/19.
 */
public class AdminAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        User user = (User) httpServletRequest.getSession().getAttribute(SystemConstants.ADMIN_AUTH_USER);
        if(user == null){
            httpServletResponse.sendRedirect("/admin/login");
            return false;
        }else{
            setPath(httpServletRequest);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public void setPath(HttpServletRequest request){
        String uri = request.getRequestURI();
        String path[] =  uri.split("/");
        if(path.length == 2){
            request.setAttribute(SystemConstants.CONTROLLER_NAME,"index");
            request.setAttribute(SystemConstants.ACTION_NAME,"index");
        }else if (path.length == 3){
            request.setAttribute(SystemConstants.CONTROLLER_NAME,path[2]);
            request.setAttribute(SystemConstants.ACTION_NAME,"index");
        }else{
            request.setAttribute(SystemConstants.CONTROLLER_NAME,path[2]);
            request.setAttribute(SystemConstants.ACTION_NAME,path[3]);
        }
    }
}
